class_name WeaponBase
extends Node2D



@onready var sprite: Sprite2D = $Sprite2D
@onready var range_area: Area2D = $RangeArea
@onready var range_collision: CollisionShape2D = $RangeArea/RangeCollisionShape
@onready var cooldown_timer: Timer = $CooldownTimer
@onready var weapon_behavior: WeaponBehavior = $WeaponBehavior


var data: ItemWeapon
# 是否正在攻击
var _attacking: bool = false
# 精灵的起始位置
var _start_position: Vector2

# 最近的目标
var _closest_target: Enemy
# 全部目标
var _targets: Array[Enemy] = []


var player: Player:
	get: return _player
var _player: Player


func _ready():
	_start_position = sprite.position
	range_area.area_entered.connect(_on_range_area_entered)
	range_area.area_exited.connect(_on_range_area_exited)



func _process(_delta: float):
	if not _attacking:
		if not _targets.is_empty():
			_update_closest_target()
		else:
			_closest_target = null
	_rotate_to_target()

	if can_attack():
		use_weapon()



## 配置武器
func setup_weapon(plyr: Player, weapon_data: ItemWeapon):
	_player = plyr
	data = weapon_data

	var shape := range_collision.shape as CircleShape2D
	shape.radius = data.weapon_stats.attack_range



func use_weapon():
	weapon_behavior.execute_attack()
	cooldown_timer.wait_time = data.weapon_stats.cooldown
	cooldown_timer.start()



## 设置攻击中状态
func set_attacking(atck: bool):
	_attacking = atck


func can_attack() -> bool:
	return cooldown_timer.is_stopped() and _closest_target



# 旋转到目标的方向
func _rotate_to_target():
	if _attacking:
		if not _closest_target or not is_instance_valid(_closest_target):
			return rotation
		var _rotation := global_position.direction_to(_closest_target.global_position).angle()
		rotation = _rotation + _calculate_spread()
	else:
		if _targets.is_empty():
			rotation = _rotation_radian()
		else:
			rotation = global_position.direction_to(_closest_target.global_position).angle()


# 更新最近的目标
func _update_closest_target():
	_closest_target = _find_closest_enemy()


# 根据玩家方向获取武器旋转的弧度
func _rotation_radian() -> float:
	if not _player:
		return 0.0
	if _player.character_orientation() > 0:
		return 0.0
	return PI


# 计算武器散布
func _calculate_spread() -> float:
	return randf_range(-1 + data.weapon_stats.accuracy, 1 - data.weapon_stats.accuracy)


# 查找最近的敌人
func _find_closest_enemy() -> Enemy:
	if _targets.is_empty():
		return null

	var closest_distance: float = INF
	var closest_enemy: Enemy = null
	for enemy: Enemy in _targets:
		var distance := global_position.distance_squared_to(enemy.global_position)
		if distance < closest_distance:
			closest_distance = distance
			closest_enemy = enemy
	return closest_enemy


func _on_range_area_entered(area: Area2D):
	if area is Enemy:
		_targets.push_back(area)


func _on_range_area_exited(area: Area2D):
	if area is Enemy:
		_targets.erase(area)
	if _targets.is_empty():
		_closest_target = null
